const radio = (() => {
    const init = async () => {
        let status = 0, counter = 0
        while (true) {
            status = await driver.devTEF668x_APPL_Get_Operation_Status()
            switch (status) {
                case 0:
                    await tuner.tableWrite(PATCH_TAB)
                    await tuner.tableWrite(START_TAB)
                    await tuner.waitMs(50)
                    break;
                case 1:
                    await tuner.tableWrite(CLOCK_TAB)
                    await tuner.tableWrite(ACTIVE_TAB)
                    await tuner.waitMs(100);
                    break;
                case 2:
                case 3:
                case 4:
                    return
                default:
                    if (++counter < 10) {
                        await tuner.waitMs(5);
                    } else {
                        return
                    }
            }
        }
    }
    const powerOn = () => {
        return driver.devTEF668x_APPL_Set_OperationMode(0)
    }
    const powerOff = () => {
        return driver.devTEF668x_APPL_Set_OperationMode(1)
    }
    const setFrequency = async (frequency) => {
        return driver.devTEF668x_Radio_Tune_To(frequency)
    }
    const setMute = () => {
        return driver.devTEF668x_Audio_Set_Mute(1)
    }
    const setUnMute = () => {
        return driver.devTEF668x_Audio_Set_Mute(0)
    }
    const setVolume = (volume) => {
        return driver.devTEF668x_Audio_Set_Volume(volume)//[-60,24]
    }
    const scan = async () => {
        for (let frequency = 8700; frequency < 10800; frequency += 10) {
            await radio.setFrequency(frequency)
            const { level, usn, wam, offset } = await driver.devTEF668x_Radio_Get_Quality_Data()
            console.log(frequency, level, usn, wam, offset)
            if (usn > 80) {
                console.log(frequency, level, usn, wam, offset, 'hello')
                // if (level > 25 && usn < 27 && wam < 23 && offset < 100) {
                // document.getElementById('stations').value += '\n' + frequency
                await tuner.waitMs(3000);
            } else {
                await tuner.waitMs(20);
            }
        }
    }
    return {
        init,
        powerOn,
        powerOff,
        setFrequency,
        setMute,
        setUnMute,
        setVolume,
        scan,
    }
})()